package com.qianchang.microfinance.view.yfbpay;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.ClearEditText;
import com.dm.library.widgets.element.DTextView;
import com.fuiou.mobile.FyPay;
import com.fuiou.mobile.FyPayCallBack;
import com.fuiou.mobile.bean.MchantMsgBean;
import com.fuiou.mobile.util.MD5UtilString;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.MyBillBean;
import com.qianchang.microfinance.bean.ThpinfoBean;
import com.qianchang.microfinance.bean.YBCheckBankCardBean;
import com.qianchang.microfinance.bean.YBMerchantPayApplyBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.mine.bill.MyBillAdapter;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.qianchang.microfinance.global.ConstantAppInfo.DEFAULT_TIME;

/********
 *   易宝支付页面详情 订单号，订单金额显示 2018.7.16
 *
 */

public class RechargePayDetailsActivity extends BaseActivity{

    @BindView(R.id.tv_get_phone_code)
    DTextView tvGetPhoneCode;
    @BindView(R.id.et_indentify_code)
    ClearEditText etMSNText;
    @BindView(R.id.tv_ordmoney_id)
    TextView tvMoney;
    @BindView(R.id.tv_orderNub_id)
    TextView tvOrderNub;

    private String orderNo;
    private static int RESCODE = 2;
    private CountDownTimer phoneDownTimer;
    private YBMerchantPayApplyBean merchantPayApplyBean;
    private YBCheckBankCardBean ybCheckBankCardBean = null;
    private String projectId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yfbpaydetails_layout);
        ButterKnife.bind(this);
             initView();
        initFuYouPay();
        initData();

        tlMerchantPayApply();           //第一步,先发送商户支付申请

    }

    //初始化富有支付
    private void initFuYouPay(){
        FyPay.setDev(true);                //此代码是配置jar包为环境配置，true 是生成，fase 测试
        FyPay.init(RechargePayDetailsActivity.this);
    }


    @Override
    protected void initView() {
        super.initView();
        setTitle("支付详情");

    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        ybCheckBankCardBean = (YBCheckBankCardBean)bundle.getSerializable("bankCard");
            projectId = bundle.getString(ConstantAppInfo.PROJECT_ID);
    }

    @Override
    protected void onResume() {
        super.onResume();
        tlMerchantPayApply();           //第一步,先发送商户支付申请
    }

    @OnClick({R.id.bt_truepay_id,R.id.tv_get_phone_code})
    public void onViewClicked(View view) {
        int vId = view.getId();
        switch (vId){
            case R.id.bt_truepay_id:            //确认支付按钮

                /****
                payConfirm();
                 ********/

                Pay();      //富友支付

                break;
            case R.id.tv_get_phone_code:            //获取短信验证码

                showRemainTime();
                if(getIsApplySus()){            //第二步，如果商户支付申请成功，重新获取支付短信（使用重新获取支付短信）
                    resendMerchantMsnCode();
                }else {
                    tlMerchantPayApply();           //第一步,先发送商户支付申请
                }

                break;
            default:
                break;
        }
    }



//    private static final int DEFAULT_TIME = 10 * 1000;//获取验证码的时间周期      测试使用，不用时候直接删掉
    //显示获取手机验证码倒计时
    private void showRemainTime() {
        tvGetPhoneCode.setEnabled(false);
        phoneDownTimer = new CountDownTimer(DEFAULT_TIME, 1000) {
            @SuppressLint("NewApi")
            @Override
            public void onTick(long millisUntilFinished) {
                int temp = (int) (millisUntilFinished / 1000);
                tvGetPhoneCode.setText("重新获取 " + temp + "S");//getString(R.string.remain_time) +
                tvGetPhoneCode.setEnabled(false);
                tvGetPhoneCode.setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.common_text_hint_color));
            }

            @SuppressLint("NewApi")
            @Override
            public void onFinish() {
                tvGetPhoneCode.setText(getString(R.string.btn_reacquire_code));
                tvGetPhoneCode.setEnabled(true);
                tvGetPhoneCode.setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.getCodeTextColor_blue));
            }
        }.start();

    }


    //设置签约申请成功标识
    private boolean isApplySus = false;
    private void setIsApplySus(boolean flag){
        this.isApplySus = flag;
    }

    private boolean getIsApplySus(){
        return isApplySus;
    }



    //商户支付申请（发起支付接口）
    private void tlMerchantPayApply(){
        String userId = DMApplication.getInstance().getmUserLoginInfo().getUserId();


        String cardtop = "";
        String cardlast = "";
        if(ybCheckBankCardBean != null){
            cardtop = ybCheckBankCardBean.getCardtop();
            cardlast = ybCheckBankCardBean.getCardlast();
        }

        HttpParams params = new HttpParams();
        params.put("userId",userId);
        params.put("cardtop",cardtop);
        params.put("cardlast",cardlast);

        show();
        DMOKHttpUtils.getInstance().post(RechargePayDetailsActivity.this, DMConstant.ApiURL.RECHARGE_PAY, params, new RequestCallBack<YBMerchantPayApplyBean>() {

            @Override
            public void onSuccess(JsonResult<YBMerchantPayApplyBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    setIsApplySus(true);    //设置商户支付申请是否成功
                    merchantPayApplyBean = response.getObject();
                    setUiData(merchantPayApplyBean);
                }else {
                    setIsApplySus(false);
                    merchantPayApplyBean = null;
                    setUiData(null);
                    ToastUtil.getInstant().show(RechargePayDetailsActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                setIsApplySus(false);
                merchantPayApplyBean = null;
                setUiData(null);
                ToastUtil.getInstant().show(RechargePayDetailsActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                setIsApplySus(false);
                merchantPayApplyBean = null;
                setUiData(null);
            }
        });
    }


    private void setUiData(YBMerchantPayApplyBean merchantPayApplyBean){
        if(merchantPayApplyBean != null && (!merchantPayApplyBean.equals(""))){
            tvMoney.setText("¥ " + merchantPayApplyBean.getAmount());
            tvOrderNub.setText(merchantPayApplyBean.getOrderNo());
            orderNo= merchantPayApplyBean.getOrderNo();
        }else {
            tvMoney.setText("");
            tvOrderNub.setText("");
        }
    }



    //重新获取支付短信（使用重新获取支付短信）

    private void resendMerchantMsnCode(){

        String requestno = "";
        if(merchantPayApplyBean != null){
            requestno = merchantPayApplyBean.getRequestno();
        }
        HttpParams params = new HttpParams();
        params.put("requestno",requestno);

        show();
        DMOKHttpUtils.getInstance().post(RechargePayDetailsActivity.this, DMConstant.ApiURL.YEPAY_AGAINPAYSMS, params, new RequestCallBack<ThpinfoBean>() {

            @Override
            public void onSuccess(JsonResult<ThpinfoBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {

                }else {
                    ToastUtil.getInstant().show(RechargePayDetailsActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(RechargePayDetailsActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(RechargePayDetailsActivity.this, msg);
            }
        });
    }

    //支付确认（使用支付确认）
    private void payConfirm(){

        String msn = etMSNText.getText().toString();
//        if (StringUtils.isEmptyOrNull(msn)) {
//            ToastUtil.getInstant().show(this, getString(R.string.input_indentity));
//            return;
//        }
        String smscode = "";
        String requestno = "";
        if(merchantPayApplyBean != null){
            requestno = merchantPayApplyBean.getRequestno();
        }
        HttpParams params = new HttpParams();
        params.put("requestno",requestno);
        params.put("validatecode",smscode);

        show();
        DMOKHttpUtils.getInstance().post(RechargePayDetailsActivity.this, DMConstant.ApiURL.YEPAY_PAYCONFIRM, params, new RequestCallBack<ThpinfoBean>() {

            @Override
            public void onSuccess(JsonResult<ThpinfoBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    startActivity(YBPaySusOrFailActivity.class);
                    setResult(RESCODE);
                    RechargePayDetailsActivity.this.finish();
                }else {
                    ToastUtil.getInstant().show(RechargePayDetailsActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(RechargePayDetailsActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(RechargePayDetailsActivity.this, msg);
            }
        });
    }


    /************************************* 富友支付SDK 2.3版本对接 ************************************************/


    private String mchntcd = "0003930F1956128";     //商户ID
    private String mchnt_key = "c3vkzglctyijj0veggbzgnbr79zuc8rf";      //
    private String backUrl= "http://47.106.131.93:8080/user/yeepay/v/fuYouPayCallBack.do";

//            //测试
//    private String mchntcd = "0002900F0280321";     //商户ID
//    private String mchnt_key = "fx45crzkmo8akn24plwvrv8ywd10zjuy";      //
//    private String backUrl= "http://180.168.100.155:14652/mobile_pay/applePay/backNotify.pay";


    //富友支付
    public void Pay() {
        String userId = DMApplication.getInstance().getmUserLoginInfo().getUserId();
        String amount = merchantPayApplyBean.getAmount();
        BigDecimal totalAmountCent =new BigDecimal(amount).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_UP);
        amount = totalAmountCent.toString();
        String ordernumber = merchantPayApplyBean.getOrderid(); //订单号,这里测试方便 直接写的随机数
        String cardNo = merchantPayApplyBean.getBankCardNo();
        String userName = merchantPayApplyBean.getBankCardName();
        String idCardNo = merchantPayApplyBean.getIdCard();
        String idCardType = "0";


        String sign = MD5UtilString.MD5Encode("02" + "|" + "2.0" + "|"
                + mchntcd.toString().trim() + "|"
                + ordernumber + "|"
                + userId.toString().trim() + "|"
                + amount + "|"
                + cardNo.toString().trim() + "|" + backUrl + "|"
                + userName.toString().trim() + "|"
                + idCardNo.toString().trim() + "|"
                + idCardType + "|" + mchnt_key);


        MchantMsgBean bean = new MchantMsgBean();
        bean.setOrderId(ordernumber);//商户获取到的订单号；
        bean.setMchntCd(mchntcd.toString().trim());// 商户号
        bean.setAmt(amount.toString().trim());
        bean.setUserId(userId.toString().trim());//用户id
        bean.setCardNo(cardNo.toString().trim());//卡号
        bean.setIDcardType(idCardType.trim());//证件类型，身份证：0，其他证件：7
        bean.setIDNo(idCardNo.toString().trim());//证件号码
        bean.setUserName(userName.toString().trim());//用户名
        bean.setBackUrl(backUrl);
        bean.setPayType("mobilePay");
        bean.setSignKey(sign);


        //调起支付
        int i = FyPay.pay(RechargePayDetailsActivity.this, bean, new FyPayCallBack() {

                    @Override
                    public void onPayComplete(String rspCode, String rspDesc, Bundle extraData) {
                        // rspCode: 0001（唯一）；
                        // rspDesc：用户取消支付（唯一）；
                        // extraData：支付传递的参数。
                        // 考虑不同的商户ui设计的不同，所以这里商户自行根据响应对界面做成功或者失败的展示
                        Log.i("responose", "rspCode = " + rspCode + " ; rspDesc = " + rspDesc);
                    }

                    @Override
                    public void onPayBackMessage(String paramString) {
                        // 支付异常处理，商户根据返回的paramString自行解析做界面展示，这里不再做技术解析说明！
                        Log.i("responose", "onPayBackMessage >>>" + paramString);

                        responEcode = paramString.substring(paramString.indexOf("<RESPONSECODE>") + 14,paramString.indexOf("</RESPONSECODE>"));
                        responMsg = paramString.substring(paramString.indexOf("<RESPONSEMSG>") + 13,paramString.indexOf("</RESPONSEMSG>"));
                        responOrdid = paramString.substring(paramString.indexOf("<ORDERID>") + 9,paramString.indexOf("</ORDERID>"));

                        paySusToCall();

                        if(responEcode != null && responEcode.equals("0000")){      //成功
                            startActivity(YBPaySusOrFailActivity.class);
                            setResult(RESCODE);
                            RechargePayDetailsActivity.this.finish();
                        }else {
                            ToastUtil.getInstant().show(getApplicationContext(),responMsg);
                            RechargePayDetailsActivity.this.finish();
                        }
                    }
                });
    }


    String responMsg;
    String responOrdid;
    private String responEcode;

    //传给后台通知
    private void paySusToCall(){
        String userId = DMApplication.getInstance().getmUserLoginInfo().getUserId();
        String orderId = merchantPayApplyBean.getOrderid();
        String code = responEcode;
        String errorMsg = responMsg;
        String requestNo = merchantPayApplyBean.getRequestno();
        String yborderid = responOrdid;


        HttpParams params = new HttpParams();
        params.put("orderId",orderId);
        params.put("code",code);
        params.put("errorMsg",errorMsg);
        params.put("projectId",projectId);
        params.put("yborderid",yborderid);
        params.put("orderNo",orderNo);
        params.put("userId",userId);
        show();
        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.RECHARGE_PAY_SUCCESE, params, new RequestCallBack<YBMerchantPayApplyBean>() {

            @Override
            public void onSuccess(JsonResult<YBMerchantPayApplyBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {

                }else{

                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(RechargePayDetailsActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(RechargePayDetailsActivity.this, msg);
            }
        });

    }



    /**
     * 清除/data/data/com.xxx.xxx/files下的内容 * * @param context
     */
    public void cleanFiles(Context context) {
        String filePath = "file:///data/user/0/com.fuiou.mobile/mobilepaysdk";
        File file = new File(filePath);

//    	getTotalSizeOfFilesInDir(file);

        if (file.exists()) {
            Log.i("wyl", " size >>> " + getTotalSizeOfFilesInDir(file));
        }
        deleteFilesByDirectory(file);
    }

    // 递归方式 计算文件的大小
    private long getTotalSizeOfFilesInDir(final File file) {
        if (file.isFile())
            return file.length();
        final File[] children = file.listFiles();
        long total = 0;
        if (children != null)
            for (final File child : children)
                total += getTotalSizeOfFilesInDir(child);
        return total;
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    /***
     * String 转 xml
     * @param paramString
     */
    private Document stringToXml(String paramString){
        if(paramString == null){
            return null;
        }
        StringReader sr = new StringReader(paramString);
        InputSource is = new InputSource(paramString);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder= null;
        Document doc = null;
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse(is);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return doc;
    }



    @Override
    protected void onDestroy() {
        cleanFiles(RechargePayDetailsActivity.this);
        super.onDestroy();
    }

}
